package com.vastcom.jwt;

import io.jsonwebtoken.*;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
import java.util.logging.Logger;

import static org.omg.PortableServer.IdAssignmentPolicyValue.USER_ID;

public class JwtUtil {
    private static  final org.slf4j.Logger logger= LoggerFactory.getLogger(JwtUtil.class);
    public static final long EXPIRATION_TIME=36000;
    public static final String SECRET="ThisIsASecret";
    public static final String TOKEN_PREFIX="Bearer ";
    public static final String HEADER_STRING="Authorization";
    public static final String USER_NAME="userName";

    public static  String generateToken(String userId){
        HashMap<String,Object> map=new HashMap<>();
        map.put(USER_NAME,userId);
        String jwt= Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512,SECRET)
                .compact();
        return TOKEN_PREFIX+jwt;
    }

    public static HttpServletRequest validateTokenAndAddUserIdToHeader(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        if (token != null) {
            try {
                Map<String, Object> body = Jwts.parser()
                        .setSigningKey(SECRET)
                        .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                        .getBody();


                return new CustomHttpServletRequest(request, body);

                //web site commence
//                String userId = (String) body.get(USER_ID); //下面这行代码很关键， 通过CustomHttpServletRequest实现了修改Request
//                 return new CustomHttpServletRequest(request, EncryptUtil.decrypt(userId));



            } catch (Exception e) {
                logger.info(e.getMessage());
                throw new TokenValidationException(e.getMessage());
            }
        } else {
            throw new TokenValidationException("Missing token");
        }
    }

    public static class CustomHttpServletRequest extends HttpServletRequestWrapper {

        private Map<String,String>claims;
        public CustomHttpServletRequest(HttpServletRequest request,Map<String,?> claims){
            super(request);
            this.claims=new HashMap<>();
            claims.forEach((k,v)->this.claims.put(k,String.valueOf(v)));

        }


        @Override
        public Enumeration<String> getHeaders(String name) {
            if(claims!=null&&claims.containsKey(name)){
                return Collections.enumeration(Arrays.asList(claims.get(name)));
            }
            return super.getHeaders(name);
        }
    }

    static class TokenValidationException extends RuntimeException{
        public TokenValidationException(String msg){
            super(msg);
        }
    }

}
